package org.changs.nav.ui.nav;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;

import org.changs.aplug.base.BaseActivity;
import org.changs.nav.R;
import org.changs.nav.delegate.global.AmapLocationTask;
import org.changs.nav.mvp.MainPresenter;

import javax.inject.Inject;

import dagger.Lazy;
import timber.log.Timber;

public class MainActivity extends BaseActivity {

    private static final String TAG_CURRENT_MAP = "TAG_CURRENT_MAP";
    public static String TAG_BACK_STACK_DEFAULT = "tag_back_stack_default";

    private MainMapFragment mMainMapFragment;
    @Inject AmapLocationTask mAmapLocationTask;
    @Inject Lazy<MainPresenter> mMainPresenter;

    @Override
    public void setup(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        new RxPermissions(this)
                .request(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .subscribe(gain -> {
                    if (!gain) {
                        Toast.makeText(this, "权限不足！", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        mAmapLocationTask.startLocation();
                    }
                });
        getMainMapFragment();
        mMainPresenter.get().attachView(MainActivity.this);
        mMainPresenter.get().handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mMainPresenter.get().handleIntent(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMainPresenter.get().detachView();
    }

    public MainMapFragment getMainMapFragment() {
        Timber.d("getMainMapFragment() called");
        if (mMainMapFragment == null) {
            mMainMapFragment = (MainMapFragment) getSupportFragmentManager().findFragmentByTag(TAG_CURRENT_MAP);
            if (mMainMapFragment == null) {
                mMainMapFragment = new MainMapFragment();
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.rl_map_content, mMainMapFragment, TAG_CURRENT_MAP)
                        .commit();
            }
        }
        return mMainMapFragment;
    }
}
